import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getDashboardStats, 
  getCheckinTrends, 
  getRoomDistribution,
  getLatestReservations,
  getUpcomingCheckins
} from '@/api/dashboard'
import { Message } from '@arco-design/web-vue'

export const useDashboardStore = defineStore('dashboard', () => {
  
  // 状态
  const stats = ref({
    totalRooms: 0,
    availableRooms: 0,
    occupancyRate: 0,
    todayCheckins: 0,
    todayCheckouts: 0,
    todayRevenue: 0,
    monthRevenue: 0,
    pendingReservations: 0
  })
  const checkinTrends = ref([])
  const roomDistribution = ref([])
  const latestReservations = ref([])
  const latestCheckins = ref([])
  const loading = ref(false)

  // 获取仪表盘统计数据
  const fetchDashboardStats = async () => {
    loading.value = true
    try {
      const data = await getDashboardStats()
      // 后端返回的字段：totalRooms, todayCheckIns, todayCheckOuts, availableRooms, 
      // occupancyRate, todayRevenue, monthRevenue, pendingReservations
      stats.value = {
        totalRooms: data.totalRooms || 0,
        availableRooms: data.availableRooms || 0,
        occupancyRate: data.occupancyRate || 0,
        todayCheckins: data.todayCheckIns || 0,
        todayCheckouts: data.todayCheckOuts || 0,
        todayRevenue: data.todayRevenue || 0,
        monthRevenue: data.monthRevenue || 0,
        pendingReservations: data.pendingReservations || 0
      }
      console.log('Dashboard统计数据加载成功', stats.value)
    } catch (error) {
      console.error('获取统计数据失败:', error)
      Message.error('获取统计数据失败')
    } finally {
      loading.value = false
    }
  }

  // 获取入住趋势数据
  const fetchCheckinTrends = async (period = 'week') => {
    try {
      const days = period === 'week' ? 7 : period === 'month' ? 30 : 365
      const data = await getCheckinTrends({ days })
      // 后端返回格式：[{ date: 'YYYY-MM-DD', count: number }]
      // 前端期望格式：[{ date: string, count: number }] 或 [{ name: string, value: number }]
      // 对于周视图，需要转换为星期几的格式
      if (period === 'week') {
        // 转换为星期几格式
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        checkinTrends.value = data.map(item => {
          const date = new Date(item.date)
          const dayOfWeek = date.getDay()
          return {
            date: weekDays[dayOfWeek],
            count: item.count
          }
        })
      } else {
        // 其他周期直接使用日期
        checkinTrends.value = data.map(item => ({
          date: item.date,
          count: item.count
        }))
      }
      console.log(`入住趋势数据加载成功（${period}）`, checkinTrends.value)
    } catch (error) {
      console.error('获取入住趋势失败:', error)
      Message.error('获取入住趋势失败')
    }
  }

  // 获取房间类型分布数据
  const fetchRoomDistribution = async () => {
    try {
      const data = await getRoomDistribution()
      // 后端返回格式：[{ type: '房型X', count: number, available: number }]
      // 前端期望格式：[{ name: string, value: number }]
      roomDistribution.value = data.map(item => ({
        name: item.type,
        value: item.count,
        available: item.available
      }))
      console.log('房间类型分布数据加载成功', roomDistribution.value)
    } catch (error) {
      console.error('获取房间类型分布失败:', error)
      Message.error('获取房间类型分布失败')
    }
  }

  // 获取最新预订数据（最近入住）
  const fetchLatestReservations = async () => {
    try {
      const data = await getLatestReservations({ limit: 5 })
      latestReservations.value = data
      console.log('最新预订数据加载成功', latestReservations.value)
    } catch (error) {
      console.error('获取最新预订数据失败:', error)
      Message.error('获取最新预订数据失败')
    }
  }

  // 获取即将入住数据
  const fetchLatestCheckins = async () => {
    try {
      const data = await getUpcomingCheckins({ limit: 5 })
      latestCheckins.value = data
      console.log('即将入住数据加载成功', latestCheckins.value)
    } catch (error) {
      console.error('获取即将入住数据失败:', error)
      Message.error('获取即将入住数据失败')
    }
  }

  // 刷新所有数据
  const refreshAll = async () => {
    try {
      await Promise.all([
        fetchDashboardStats(),
        fetchCheckinTrends('week'),
        fetchRoomDistribution(),
        fetchLatestReservations(),
        fetchLatestCheckins()
      ])
      console.log('Dashboard所有数据刷新完成')
    } catch (error) {
      console.error('刷新数据失败:', error)
    }
  }

  return {
    // 状态
    stats,
    checkinTrends,
    roomDistribution,
    latestReservations,
    latestCheckins,
    loading,
    
    // 方法
    fetchDashboardStats,
    fetchCheckinTrends,
    fetchRoomDistribution,
    fetchLatestReservations,
    fetchLatestCheckins,
    refreshAll
  }
})
